const fs = require('fs')
const path = require('path')

exports.compile = function(filePath, dstPath) {
    fs.stat(filePath, (err, stats) => {
        if (!stats.isFile()) {
            console.warn('This is not file')
            return
        }
        handle(filePath, dstPath)
    })
}

function handle(srcPath, dstPath) {
    let dir = path.dirname(srcPath)
    let data = fs.readFileSync(srcPath).toString()
    /* @data
        ... ...
        ... @HTML{index.html} ...
        ... ...
    */
    let html = /@HTML{(.*?)}/.exec(data)
    let htmlPath = html ? html[1] : ''
    /* @htmlPath
        index.html
    */
    htmlPath = path.isAbsolute(htmlPath) ? htmlPath : path.join(dir, htmlPath)
    let htmlData = fs.readFileSync(htmlPath).toString()
    htmlData = htmlData.replace(/\r\n|$/g, '\\n').replace(/\n/g, '\\n')
    /* @htmlData
        <h1>
            hello world
        </h1>
        ===============
        <h1>\n    hello world\n</h1>\n
    */
    fs.writeFile(dstPath, data.replace(/@HTML{(.*?)}/i, htmlData), (err) => {
        if (err) throw err;
        console.log('The file has been saved!');
    })
}